package com.nfl.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.net.ParseException;

public class HttpUtil {
	/**
	 * post请求
	 * 
	 * @param url
	 * @param list
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public static String postRequest(String url,
			List<BasicNameValuePair> bnvList) throws ParseException,
			IOException {
		String result = "";
		HttpClient client = new DefaultHttpClient();

		HttpPost post = new HttpPost(url);

		HttpParams httpParams = client.getParams();

		HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
		HttpConnectionParams.setSoTimeout(httpParams, 30000);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (null != bnvList) {
			for (BasicNameValuePair param : bnvList) {
				params.add(param);
			}
		}

		HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
		post.setEntity(entity);

		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			InputStream in = response.getEntity().getContent();
			result = readString(in);
		}

		return result;
	}

	/**
	 * get请求
	 * 
	 * @param url
	 * @return
	 */
	public static String getRequest(String url) {
		String result = "";
		HttpClient client = new DefaultHttpClient();

		HttpGet get = new HttpGet(url);

		try {
			HttpParams httpParams = client.getParams();

			HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);

			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream in = response.getEntity().getContent();
				result = readString(in);
			}
		} catch (Exception e) {
			// 连接超时
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 用于处理HttpClient的请求结果，防止中文乱码
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private static String readString(InputStream in) throws IOException {
		byte[] data = new byte[2048];
		int length = 0;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		while ((length = in.read(data)) != -1) {
			bout.write(data, 0, length);
		}
		return new String(bout.toByteArray(), "UTF-8");
	}
}
